#!/usr/bin/python
# -*- coding:utf-8 -*-
# @author  : Chestnut
# @time    : 2025/6/26 09:56
# @function: What can I do.
# @version : V1
import csv
import os.path
import time
import tkinter
from tkinter import filedialog, Tk, ttk


# 定义TXT文件路径和CSV文件路径
class TransExtendName:
    def __init__(self):
        self.csv_files = []

    def read_file(self):
        self.t1.delete("1.0", tkinter.END)
        CSV_files = filedialog.askopenfilenames(filetypes=[
            ("文本文件", "*.csv"),
            ("所有文件", "*.*")
        ])
        if len(CSV_files) == 0:
            self.t1.insert(tkinter.END, "No Files Selected")
            pass
        else:
            for CSV_file in CSV_files:
                self.t1.insert(tkinter.END, CSV_file + "\n")
            self.t1.insert(tkinter.END, f"共选择{len(CSV_files)}个文件")
            self.csv_files = CSV_files

    def transExtendName(self):
        self.t1.delete("1.0", tkinter.END)
        for csv_file in self.csv_files:
            txt_file = csv_file[0:-4] + ".txt"
            with open(csv_file, 'r') as csvfile, open(txt_file, 'w') as txtfile:
                reader = csv.reader(csvfile)
                # self.p1.config(maximum=sum(1 for row in reader))
                for count, line in enumerate(reader):
                    txtfile.write("# ")
                    for col in line:
                        txtfile.write(col + " ")
                    txtfile.write('\n')
                    # self.p1['value'] = count + 1
                    # self.p1.update()
                self.t1.insert(tkinter.END, f"{txtfile.name}->{csvfile.name}\n")
        self.t1.insert(tkinter.END, f"共转化了{len(self.csv_files)}个文件")
        self.t1.see(tkinter.END)

    def main_window(self):
        root = Tk()
        self.file_name = tkinter.StringVar()
        root.title("Transform TXT ExtendName")
        tkinter.Label(root, text="选择文件").grid(row=0, column=0)
        self.e1 = tkinter.Entry(root, width=50, textvariable=self.file_name)
        self.t1 = tkinter.Text(root)
        tkinter.Button(root, text="Browse", command=self.read_file).grid(row=0, column=2)
        tkinter.Button(root, text="Start", command=self.transExtendName, width=80).grid(row=3, column=0, columnspan=3)
        self.p1 = ttk.Progressbar(root, orient=tkinter.HORIZONTAL, mode='determinate')
        root.bind("<Return>", self.transExtendName)
        self.e1.grid(row=0, column=1)
        self.t1.grid(row=1, column=0, columnspan=3)
        self.p1.grid(row=2, column=0, columnspan=3, sticky=tkinter.EW)
        root.mainloop()


myapp = TransExtendName()
myapp.main_window()
